package com.fhx.core.utils

import android.app.Activity
import android.util.Log

/**
 * Activity栈管理
 */
object ActivityStackManager {
    private val activities by lazy { mutableListOf<Activity>() }

    @JvmStatic
    fun add(activity: Activity)= activities.add(activity)

    @JvmStatic
    fun remove(activity: Activity){
        if(activities.contains(activity)){
            activities.remove(activity)
            activity.finish()
        }
    }
    @JvmStatic
    fun remove02(butClazz: Class<*>){
        try {
            for (i in activities.indices.reversed()) {
                val activity: Activity = activities.get(i)
                if (butClazz == activity) {
                    activity.finish()
                    activities.removeAt(i)
                }
            }
        } catch (e: Exception) {
        }
    }

    @JvmStatic
    fun getTop():Activity? = if(activities.isEmpty()) null else activities[activities.size - 1]

    @JvmStatic
    fun finishAll(){
        try {
            //这里最好不用forEach
            for (i in activities.indices.reversed()) {
                val activity: Activity = activities.removeAt(i)
                activity.finish()
            }
        } catch (e: Exception) {
            System.exit(0)
        }
    }

    //除了某个对象，全都结束
    @JvmStatic
    fun finishAllBut(butObj: Activity) {
        try {
            for (i in activities.indices.reversed()) {
                val activity: Activity = activities.get(i)
                if (butObj !== activity) {
                    activity.finish()
                    activities.removeAt(i)
                }
            }
        } catch (e: Exception) {
        }
    }

    //除了某个类的对象，全都结束
    @JvmStatic
    fun finishAllBut(butClazz: Class<*>) {
        try {
            for (i in activities.indices.reversed()) {
                val activity: Activity = activities.get(i)
                if (activity.javaClass != butClazz) {
                    activity.finish()
                    activities.removeAt(i)
                }
            }
        } catch (e: Exception) {
        }
    }

    //是否包含某个类
    @JvmStatic
    fun contains(butClazz: Class<*>):Boolean {
        try {
            for (i in activities.indices) {
                val activity: Activity = activities.get(i)
                if (activity.javaClass == butClazz) {
                    return true
                }
            }
        } catch (e: Exception) {
        }
        return false
    }
    fun recreateAllOtherActivity(activity: Activity) {
        var i = 0
        val size: Int = activities.size
        while (i < size) {
            if (null != activities.get(i) && activities.get(i) !== activity) {
                activities.get(i).recreate()
            }
            i++
        }
    }
}